package com.bmsym.astrolog;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;


public class AstroLogActivity
        extends Activity
        implements TextToSpeech.OnInitListener {

    private TextToSpeech tts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        tts = new TextToSpeech(this, this);

        initCatalog();

        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        LinearLayout logView = (LinearLayout) findViewById(R.id.log_entry_layout);
        for (int i = 0; i < 5; ++i) {
            View view = inflater.inflate(R.layout.log_entry_layout, logView, false);
            view.getId();
            view.setLayoutParams(new LinearLayout.LayoutParams(
                    ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
            logView.addView(view);
        }

        View menuButton = findViewById(R.id.menu);
        menuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // vocalize("Click it good!");
            }
        });
    }

    private void initCatalog() {
        // http://bit.ly/eogiOV
        Spinner catalogSpinner = (Spinner) findViewById(R.id.catalog_spinner);

        // The key to use for reading the color from the Map
        final String[] from = new String[]{"catalog"};
        final int[] to = new int[]{android.R.id.text1};

        final List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for (String catalog : getResources().getStringArray(R.array.catalogs)) {
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("catalog", catalog);
            data.add(map);
        }
        SimpleAdapter catalogAdapter = new SimpleAdapter(this, data, android.R.layout.simple_spinner_item, from, to);
        catalogAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        catalogSpinner.setAdapter(catalogAdapter);
        catalogSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            @SuppressWarnings("unchecked")
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
                final Map<String, String> data = (Map<String, String>) adapterView.getItemAtPosition(pos);
                EditText logSubject = (EditText) findViewById(R.id.log_subject);

                if ("".equals(data.get("catalog"))) {
                    logSubject.setInputType(InputType.TYPE_CLASS_TEXT);
                    logSubject.setHint(getString(R.string.hint_log_subject));
                    // vocalize("Null pointer exceptions are the enemy!");
                } else {
                    logSubject.setInputType(InputType.TYPE_CLASS_NUMBER);
                    logSubject.setHint(getString(R.string.hint_log_subject));
                    // vocalize("Null pointer exceptions are the enemy!");
                }
                logSubject.selectAll();
                logSubject.requestFocus();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                findViewById(R.id.menu);
                EditText logSubject = (EditText) findViewById(R.id.log_subject);
                logSubject.setInputType(InputType.TYPE_CLASS_TEXT);
            }
        });
    }

    private void updateUi() {
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            int result = tts.setLanguage(Locale.UK);

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS", "This Language is not supported");
            }
        } else {
            Log.e("TTS", "Initialization Failed!");
        }
    }

    private void vocalize(String text) {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    // When user clicks button, calls AsyncTask.
    // Before attempting to fetch the URL, makes sure that there is a network connection.
    public void myClickHandler(View view) {
        // Gets the URL from the UI's text field.
        String stringUrl = "http://en.wikipedia.org/wiki/Messier_47";
        ConnectivityManager connMgr = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadWebpageText().execute(stringUrl);
        }
    }

    // Uses AsyncTask to create a task away from the main UI thread. This task takes a
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    private class DownloadWebpageText extends AsyncTask<String, String, String> {
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            //textView.setText(result);
        }

        @Override
        protected String doInBackground(String... urls) {
            // params comes from the execute() call: params[0] is the url.

            try {
                return downloadUrl(urls[0]);
            } catch (IOException e) {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }

        // Given a URL, establishes an HttpUrlConnection and retrieves
        // the web page content as a InputStream, which it returns as
        // a string.
        private String downloadUrl(String path) throws IOException {
            InputStream is = null;
            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 500;

            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                // Starts the query
                conn.connect();
                int response = conn.getResponseCode();
                // Log.d(DEBUG_TAG, "The response is: " + response);
                is = conn.getInputStream();

                // Convert the InputStream into a string
                return readIt(is, len);

                // Makes sure that the InputStream is closed after the app is
                // finished using it.
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }

        // Reads an InputStream and converts it to a String.
        public String readIt(InputStream stream, int len) throws IOException {
            Reader reader = new InputStreamReader(stream, "UTF-8");
            char[] buffer = new char[len];
            reader.read(buffer);
            return new String(buffer);
        }
    }

}
